<?php
/**
 * Controller is the customized base controller class.
 * All controller classes for this application should extend from this base class.
 */
class MyCActiveRecord extends CActiveRecord
{

	public function behaviors() { 
		return array( 
						'LoggableBehavior'=> 'application.modules.auditTrail.behaviors.LoggableBehavior',
					);
	}
	
	public function beforeSave()
	{
		try{
			parent::beforeSave();
			
			if($this->isNewRecord)
			{
				foreach($this->attributes as $key => $value)
				{
					if(substr($key,-6) == 'creado')
					{
						$this->$key = new CDbExpression('NOW()');
					}
					
					if(strrpos($key,'creado_usuario_id')!==false)
					{
						$this->$key = user()->getId();
					}
					
					if(substr($key,-10) == 'modificado')
					{
						$this->$key = null;
					}
					
					if(strrpos($key,'modificado_usuario_id')!==false)
					{
						$this->$key = null;
					}
					
				}
			}
			else
			{
				foreach($this->attributes as $key=>$value)
				{
					if(substr($key,-6) == 'creado')
					{
						$this->$key = date('Y-m-d H:i:s', strtotime(str_replace('/','-',$value)));
					}
					
					if(substr($key,-10) == 'modificado')
					{
						$this->$key = new CDbExpression('NOW()');
					}
					
					if(strrpos($key,'modificado_usuario_id')!==false)
					{
						$this->$key = user()->getId();
					}
					
				}
			}
			return true;
		}
		catch(Exception $e)
		{
			var_dump($e);exit;
			throw new Exception(t("Problema"));
		}	
		
		
	}
	

	public function afterFind()
	{
		try{
			parent::afterFind();
			foreach($this->attributes as $key=>$value)
			{
				if(substr($key,-6) == 'creado' || substr($key,-10) == 'modificado')
				{
					$this->$key = ($this->$key != '0000-00-00 00:00:00' && !is_null($this->$key))?date('d/m/Y H:i:s', strtotime(str_replace('-','/',$this->$key))):'';
				}
			}

			return true;
		}
		catch(Exception $e)
		{
			var_dump($e);exit;
			throw new Exception(t("Problema"));
		}
		
	}
}